package org.example.demo1;

import java.sql.*;

public class zuoye1 {
    public static void main(String[] args) {
        String url = "jdbc:mysql://localhost:3306/abc?allowPublicKeyRetrieval=true&useSSL=false&serverTimezone=Asia/Shanghai";
        String user = "root";
        String password = "123456";
        Connection con = null;
        PreparedStatement ps = null;
        ResultSet resultSet = null;
        int id = 0;
        try {
            Class.forName("com.mysql.cj.jdbc.Driver");
            con = DriverManager.getConnection(url, user, password);
            System.out.println(con);

            //开始搬运数据
            //con.createStatement();更安全,容易出sql注入bug
            //con.prepareStatement();更便捷,不容易出sql注入bug
            String sql = "select * from user where username=? and password=?";
            ps = con.prepareStatement(sql);
            ps.setString(1, "admin");
            ps.setString(2, "123456");
            resultSet = ps.executeQuery();
            while (resultSet.next()) {
                id = resultSet.getInt("id");//字段的名称或者序号
                System.out.println(resultSet.getString("username"));
                System.out.println(resultSet.getString("email"));

            }


        } catch (ClassNotFoundException e) {
            throw new RuntimeException(e);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        } finally {//后开的先关
            if (con != null) {
                try {
                    con.close();
                    System.out.println("数据库连接已关闭。");
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            if (ps != null) {
                try {
                    ps.close();
                    System.out.println("数据库连接已关闭。");
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            if (resultSet != null) {
                try {
                    resultSet.close();
                    System.out.println("数据库连接已关闭。");
                } catch (SQLException e) {
                    throw new RuntimeException(e);
                }

            }
        }
    }
}